package org.lewis.woman.service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.lang.StringUtils;
import org.lewis.common.domain.Tag;
import org.lewis.common.domain.User;
import org.lewis.common.jdbc.QueryHelper;
import org.lewis.common.service.TagService;

import com.tocersoft.framework.core.annotations.Component;
import com.tocersoft.framework.core.cache.OSCacheManager;

@Component
public class TagSercviceImpl implements TagService {

	public static final String ADDTAG = "insert into ts_tag (name,songs,rank,type) values (?,?,?,?)";

	// 缓存过期时间
	public static final int tagCacheTime = 24 * 60 * 60;

	private final static OSCacheManager cacheMang =OSCacheManager.getInstance();

	public long addTag(Tag tag) {
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = QueryHelper.getConnection().prepareStatement(ADDTAG,
					PreparedStatement.RETURN_GENERATED_KEYS);
			ps.setObject(1, tag.getName());
			ps.setObject(2, tag.getSongs());
			ps.setObject(3, tag.getRank());
			ps.setObject(4, tag.getType());
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			return rs.next() ? rs.getLong(1) : -1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(rs);
			DbUtils.closeQuietly(ps);
		}
		removeCache();
		return 0;
	}

	public List<Tag> queryAll(boolean cache) {
		String sql="select id,name,songs,rank,type from ts_tag order by rank desc ";
		if(cache){
			return QueryHelper.queryCache(Tag.class, "all_tags_cache", tagCacheTime,sql);
		}else{
			return QueryHelper.query(Tag.class, sql);
		}
	}

	public void updateTag(long id, String name, int rank, int type) {
		QueryHelper.update(
				"update ts_tag set name=? , rank=?,type=? where id=? ", name,
				rank, type, id);
		removeCache();
	}

	public List<Tag> queryByType(int type) {
		String sql = "select id,name,songs,rank,type from ts_tag where type=? order by rank desc ";
		return QueryHelper.queryCache(Tag.class, "tags_type_" + type,
				tagCacheTime, sql, type);
	}

	public void removeCache() {
		cacheMang.removeCache("kvtags_cache");
		cacheMang.removeCache("all_tags_cache");
		cacheMang.removeCache("tags_type_0");
		cacheMang.removeCache("tags_type_1");
		cacheMang.removeCache("tags_type_2");
	}

	@SuppressWarnings("unchecked")
	public List<Tag> getUserTags(User user) {
		Map<Long, Tag> kvTags = (Map<Long, Tag>) cacheMang.getCache(
				"kvtags_cache", tagCacheTime);
		if (kvTags == null) {
			// 所有tags
			List<Tag> allTags = this.queryAll(true);
			// 将tags建立k-v
			kvTags = new HashMap<Long, Tag>();
			for (Tag tag : allTags) {
				kvTags.put(tag.getId(), tag);
			}
			cacheMang.putCache("kvtags_cache", kvTags);
		}

		// 用户选中tags
		List<Tag> selectTags = new ArrayList<Tag>();

		if (StringUtils.isNotBlank(user.getTags())) {
			// 用户tags id
			String[] userTagIds = user.getTags().split(",");
			for (int i = 0; i < userTagIds.length; i++) {
				selectTags.add(kvTags.get(Long.parseLong(userTagIds[i])));
			}
		}

		return selectTags;
	}

	public void updateTagSongs(String... name) {
		String sql = "update ts_tag set songs=songs+1 where name=?";
		for (int i = 0; i < name.length; i++) {
			QueryHelper.update(sql, name[i]);
			// 处理缓存更新
			clearMinCache("all_tags_cache", name[i]);
			clearMinCache("tags_type_0", name[i]);
			clearMinCache("tags_type_1", name[i]);
			clearMinCache("tags_type_2", name[i]);
		}
		cacheMang.removeCache("kvtags_cache");
	}

	@SuppressWarnings("unchecked")
	private void clearMinCache(String cachekey,String name) {
		List<Tag> cacheAllTags = (List<Tag>) cacheMang.getCache(cachekey);
		if (cacheAllTags != null) {
			List<Tag> newCache = new ArrayList<Tag>();
			for (Tag tag : cacheAllTags) {
					Tag newtag=tag;
					if (newtag.getName().equals(name)) {
						newtag.setSongs(newtag.getSongs() + 1);
						newCache.add(newtag);
					}else{
						newCache.add(newtag);
					}
			}
			cacheMang.putCache(cachekey, newCache);
		}
	}

}
